const Record = require("../model/record");
const { Op } = require("sequelize");

module.exports = class RecordService {
  static async addRecord(record) {
    const [result, created] = await Record.findOrCreate({
      where: { name: record.name, pos: record.pos },
      defaults: record,
    });
    if (!created) {
      // 如果记录已存在，则更新它
      await result.update(record);
      await result.reload();
    }
    return result.toJSON();
  }

  static async deleteRecord(id) {
    const result = await Record.destroy({
      where: {
        id,
      },
    });
    return result > 0;
  }

  static async updateRecord(id, record) {
    await Record.update(record, {
      where: {
        id,
      },
    });
    const res = await Record.findOne({
      where: {
        id,
      },
    });
    return res.toJSON();
  }

  static async getRecordListByQuery(query) {
    const where = { ...query };
    if (query.startAt && Array.isArray(query.startAt)) {
      const [startDate, endDate] = query.startAt;
      where.startAt = {
        [Op.between]: [
          startDate,
          endDate + " 23:59:59", // 将结束日期调整到当天的最后一秒
        ],
      };
    }
    const result = await Record.findAll({
      where,
    });
    return result.map((item) => item.toJSON());
  }

  static async getRecordList() {
    const result = await Record.findAll();
    return result.map((item) => item.toJSON());
  }
};
